import { Request, Response, NextFunction } from "express";
import { toCamelCase } from "@/utils/index";
import lodash from "lodash";

// 移除不必要参数
const clearParams = (data: any, key: string): any => {
  const params = lodash.cloneDeep(data);
  delete params[key];
  return !!Object.keys(params).length ? params : null;
};

// 响应格式化中间件
export const responseMiddleware = (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  // 需要重新包装的 send 方法
  const originalSend = res.send;

  res.send = function (body: any) {
    if (!res.locals.hasSent) {
      res.locals.hasSent = true;
      const bodyJson = JSON.parse(body);
      // 默认的成功状态
      const responseStructure = {
        data:
          bodyJson?.message && res.statusCode !== 200
            ? null
            : clearParams(bodyJson, "message"),
        code: res.statusCode || 200,
        msg: bodyJson?.message ?? "",
        success: res.statusCode === 200 || res.statusCode === 201,
        time: `${Date.now()}`,
      };
      // 调用原始的 send 方法，传递处理后的响应结构
      return originalSend.call(res, toCamelCase(responseStructure));
    } else {
      return originalSend.call(res, body);
    }
  };

  next();
};
